/**
 * Http请求工具类
 * Created by yangyao on 2017/7/16.
 */
import Constans from './Constants'

/**
 * 创建一个新的XMLHttpRequest对象
 * @returns {XMLHttpRequest}
 */
function createXhr () {
  let xhr = new XMLHttpRequest()
  return xhr
}

function Response () {
  this.httpStatus = 200
  this.success = false
  this.body = ''
  this.resp = {}
  this.call = function (resp) {
    console.log('默认回调函数', resp)
  }
}

Response.prototype.initData = function (xhr) {
  this.httpStatus = xhr.status
  this.body = xhr.responseText
  let data = {}
  try {
    data = JSON.parse(xhr.responseText)
  } catch (e) {
    console.warn('转换JSON数据失败')
  }
  this.resp = {
    data: {
      status: xhr.status,
      dataType: xhr.responseType,
      xhr: xhr,
      body: xhr.responseText,
      data: data
    }
  }
  this.invokeCall()
}

Response.prototype.then = function (call) {
  this.call = call
}

Response.prototype.invokeCall = function () {
  console.log('执行回调函数')
  this.call(this.resp)
}

function doRequest (options) {
  if (!options.url.startsWith('https://') && !options.url.startsWith('http://')) {
    options.url = Constans.CommonApiUrl.ECURL + '/' + options.url
  }
  options.url += '?t=' + new Date().getTime()
  let baseParams = window.localStorage.getItem(httpBaseParamsCacheKey)
  if (baseParams !== '') {
    let params = JSON.parse(baseParams)
    for (let k in params) {
      options.url += ('&' + k + '=' + params[k])
    }
  }
  if (options.params) {
    for (let k in options.params) {
      options.url += ('&' + k + '=' + options.params[k])
    }
  }
  let xhr = createXhr()
  xhr.open(options.method, options.url, options.async)
  if (options.contentType) {
    xhr.setRequestHeader('Content-Type', options.contentType)
  }
  let resp = new Response()
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      resp.initData(xhr)
    }
  }
  xhr.send(options.sendData)
  return resp
}

let contentType = {
  'FORM': 'application/x-www-form-urlencoded',
  'JSON': 'application/json; charset=utf-8'
}

const httpBaseParamsCacheKey = 'httpBaseParams'

export default {
  /**
   * 发起一个GET请求
   * @param url
   * @param params
   * @param config
   */
  get: function (url, params, configs) {
    if (!params) {
      params = {}
    }
    return doRequest({
      async: true,
      method: 'GET',
      contentType: contentType.FORM,
      url: url,
      params: params,
      sendData: null
    })
  },
  /**
   * 发起一个POST请求，发送JSON数据，Content-Type为application/json; charset=UTF-8
   * @param url
   * @param data
   * @param config
   */
  post: function (url, data, configs, vue) {
    return doRequest({
      async: true,
      method: 'POST',
      contentType: contentType.JSON,
      url: url,
      sendData: JSON.stringify(data)
    })
  },
  /**
   * 发起一个POST表单请求，发送FORM表单数据
   * @param url
   * @param data
   * @param config
   */
  postForm: function (url, data, configs) {
    let dataStr = ''
    let count = 0
    let len = 0
    for (let k in data) {
      len += 1
      console.log(k)
    }
    for (let k in data) {
      if (count !== len - 1) {
        dataStr += (k + '=' + data[k] + '\n')
      } else {
        dataStr += (k + '=' + data[k])
      }
      count += 1
    }
    // dataStr = dataStr.substring(0, dataStr.length - 1)
    return doRequest({
      async: true,
      method: 'POST',
      contentType: contentType.FORM,
      url: url,
      sendData: dataStr
    })
  },
  /**
   * 配置公共请求参数，发送http请求时会追加到url末尾作为url参数
   * @param key 参数key
   * @param value 参数value
   */
  pushBaseParam: function (key, value) {
    let httpBaseParamsCache = window.localStorage.getItem(httpBaseParamsCacheKey)
    let httpBaseParams
    if (httpBaseParamsCache === null || httpBaseParamsCache === '') {
      httpBaseParams = {}
    } else {
      httpBaseParams = JSON.parse(httpBaseParamsCache)
    }
    httpBaseParams[key] = value
    window.localStorage.setItem(httpBaseParamsCacheKey, JSON.stringify(httpBaseParams))
  }
}
